<template>
  <div class="page">
    <h2>每日故事</h2>
    <div v-if="loading" class="yigu-loading">加载中...</div>
    <div v-else class="yigu-story">
      <div class="yigu-title">{{ story.title }}</div>
      <div class="yigu-content" v-html="story.content"></div>
      <button @click="fetchYiGu(getRandomStoryId())">换一个</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const story = ref({ title: '', content: '' })
const loading = ref(true)
const appId = 'mrfjmtn2heawpjif'
const appSecret = 'wctcTdWBenOALNujImfp9F1rZZkTPOXF'

function getRandomStoryId() {
  // 假设 story_id 范围为 101400~101499
  return 101400 + Math.floor(Math.random() * 100)
}

async function fetchYiGu(storyId) {
  loading.value = true
  try {
    const id = storyId
    const res = await fetch(`https://www.mxnzp.com/api/story/details?story_id=${id}&app_id=${appId}&app_secret=${appSecret}`)
    const data = await res.json()
    if (data.code === 1 && data.data) {
      let content = data.data.content || '无'
      // 1. 所有换行符替换为<br>
      content = content.replace(/\r\n|\n|\r/g, '<br>')
      // 2. 2个及以上连续空格也替换为<br>
      content = content.replace(/ {2,}/g, '<br>')
      // 3. 首行缩进2个全角空格（如已换行则每段首行都缩进）
      content = content.split('<br>').map((line, idx) => idx === 0 ? '　　' + line : line).join('<br>')
      story.value = {
        title: data.data.title || '无',
        content
      }
    } else {
      story.value = { title: data.msg || '获取失败', content: '' }
    }
  } catch (e) {
    story.value = { title: '获取失败，请检查网络', content: '' }
  } finally {
    loading.value = false
  }
}

// 页面加载时用随机 story_id
fetchYiGu(getRandomStoryId())
</script>

<style>
.page {
  text-align: center;
  margin-top: 60px;
}
button {
  margin-top: 20px;
  padding: 8px 24px;
  background: #42b983;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}
button:hover {
  background: #369870;
}
.yigu-content {
  margin: 20px auto;
  text-align: left;
  max-width: 600px;
  font-size: 1.1rem;
  line-height: 2;
  border-radius: 10px;
  padding: 24px 20px;
  box-shadow: 0 2px 8px #f8c6d8;
  word-break: break-all;
  height: 320px;
  overflow-y: auto;
  /* background: none; */
  box-sizing: border-box;
}
@media (max-width: 600px) {
  .yigu-content {
    height: 40vh;
    max-width: 98vw;
    padding: 12px 6px;
  }
}
/* 自定义滚动条样式，兼容主流浏览器 */
.yigu-content::-webkit-scrollbar {
  width: 8px;
}
.yigu-content::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #f78fb3 0%, #f672a7 100%);
  border-radius: 6px;
  border: none;
}
.yigu-content::-webkit-scrollbar-track {
  background: linear-gradient(180deg, #ffe0ef 0%, #f8c6d8 100%);
  border-radius: 6px;
}
</style> 